//
//  ViewController.m
//  通讯录LV2.0
//
//  Created by dllo on 16/8/5.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ViewController.h"
#import "NSString+Common.h"
#import "ContactRow.h"
#import "ContactInfoController.h"

#define kTableCellReuse @"tableCell"

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableDictionary *contactDic;
@property (nonatomic, strong) NSArray *allkeys;

@property (nonatomic, strong) NSFileManager *manager;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createTableView];
    _manager = [[NSFileManager alloc]init];
    
    // 如果文件不存在，创建
    if (![_manager fileExistsAtPath:[self getFilePath]]) {
        [self createFile];
    }
    [self unArchiverFile];
    
    // 如果文件反归档返回的字典为空，送工程中读取文件
    if (_contactDic == nil) {
        [self handleData];
    }
    
    _allkeys = [[_contactDic allKeys]sortedArrayUsingSelector:@selector(compare:)];
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)handleData
{
    _contactDic = [NSMutableDictionary dictionary];
    NSString *path = [[NSBundle mainBundle]pathForResource:@"DLS160710" ofType:@"plist"];
    NSMutableArray *arrOfContact = [NSMutableArray arrayWithContentsOfFile:path];
    
    for (NSDictionary *dic in arrOfContact) {
        NSString *capital = [dic[@"name"] CapitalOfName] ;
        capital = [capital PureLetters]? capital: @"#";
        [_contactDic setObject:[NSMutableArray array] forKey:capital];
    }
    for (NSDictionary *dic in arrOfContact) {
        NSString *capital = [dic[@"name"] CapitalOfName];
        capital = [capital PureLetters]? capital: @"#";
        ContactRow *row = [[ContactRow alloc]init];
        [row setValuesForKeysWithDictionary:dic];
        [_contactDic[capital] addObject:row];
    }
    [self archiverFile:_contactDic];
    
}

#pragma mark - 归档，反归档
- (void)archiverFile:(NSDictionary *)dic
{
    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archiver encodeObject:dic forKey:@"contact"];
    [archiver finishEncoding];
    [data writeToFile:[self getFilePath] atomically:YES];
}

- (void)unArchiverFile
{
    NSData *data = [NSData dataWithContentsOfFile:[self getFilePath]];
    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    _contactDic = [unArchiver decodeObjectForKey:@"contact"];
    [unArchiver finishDecoding];
}

#pragma mark - file
- (void)createFile
{
    [_manager createFileAtPath:[self getFilePath] contents:nil attributes:nil];
}

- (NSString *)getFilePath
{
    NSString *pathOfDoc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)  firstObject];
    NSLog(@"%@", pathOfDoc);
    NSString *path = [pathOfDoc stringByAppendingPathComponent:@"contact.plist"];
    return path;
}

- (void)createTableView
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - 64) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kTableCellReuse];
    
}

#pragma mark - 删除和添加联系人
- (void)deleteContactAtIndexPath:(NSIndexPath *)indexPath andTableView:(UITableView *)tableView
{
    NSMutableArray *deleteArr = [_contactDic objectForKey:_allkeys[indexPath.section]];
    [deleteArr removeObjectAtIndex:indexPath.row - 1];
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    if ([deleteArr firstObject] == nil) {
        [_contactDic removeObjectForKey:_allkeys[indexPath.section]];
        _allkeys = [[_contactDic allKeys]sortedArrayUsingSelector:@selector(compare:)];
        [tableView reloadData];
    }
    
    [self archiverFile:_contactDic];
}

#pragma mark - table data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_contactDic allKeys].count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[_contactDic objectForKey:_allkeys[section]] count] + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableCellReuse];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.layer.borderWidth = 0.5;
    cell.layer.borderColor = [UIColor lightGrayColor].CGColor;
    if (indexPath.row == 0) {
        cell.textLabel.text = _allkeys[indexPath.section];
        cell.imageView.image = nil;
        cell.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    } else {
        cell.textLabel.text = [[_contactDic objectForKey:_allkeys[indexPath.section]][indexPath.row - 1] name];
        cell.backgroundColor = [UIColor colorWithRed:(arc4random()%6 + 230)/235.0 green:(arc4random()%6 + 220)/225.0 blue:0.95 alpha:1];
        cell.imageView.image = [UIImage imageNamed:@"man"];
    }
    return cell;
}

#pragma mark - table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 20;
    } else {
        return 55;
    }
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSMutableArray *array = [NSMutableArray array];
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [self deleteContactAtIndexPath:indexPath andTableView:tableView];
    }];
    deleteAction.backgroundColor = [UIColor redColor];
    
    UITableViewRowAction *insertAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"插入" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        ContactInfoController *contactInfo = [[ContactInfoController alloc]initWithNibName:@"ContactInfoController" bundle:[NSBundle mainBundle]];;
        [self.navigationController pushViewController:contactInfo animated:YES];
    }];
    insertAction.backgroundColor = [UIColor orangeColor];
    return @[deleteAction, insertAction];
}


- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [_tableView setEditing:editing animated:YES];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return NO;
    }
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return UITableViewCellEditingStyleNone;
    } else {
        return UITableViewCellEditingStyleDelete;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return;
    }
    ContactInfoController *contactInfo = [[ContactInfoController alloc]initWithNibName:@"ContactInfoController" bundle:[NSBundle mainBundle]];
    contactInfo.model = [_contactDic objectForKey:_allkeys[indexPath.section]][indexPath.row - 1];
    contactInfo.indexPath = indexPath;
    
    [self.navigationController pushViewController:contactInfo animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.navigationController.viewControllers.count < 2) {
        return;
    }
    ContactInfoController *contactInfo = [self.navigationController.viewControllers objectAtIndex:0];
    self.navigationController.viewControllers = @[self,  contactInfo];
    self.navigationItem.hidesBackButton = YES;
    if (contactInfo &&(contactInfo.model.name !=contactInfo.modelOfChange.name  || contactInfo.model.phoneNumber != contactInfo.modelOfChange.phoneNumber || contactInfo.model.family != contactInfo.modelOfChange.family )) {
        if (![contactInfo.model.name isEqualToString:contactInfo.modelOfChange.name]) {
            UITableViewCell *cell = [_tableView cellForRowAtIndexPath:contactInfo.indexPath];
            cell.textLabel.text = contactInfo.model.name;
            [_tableView reloadData];
        }
        NSString *capital = [contactInfo.modelOfChange.name CapitalOfName];
        capital = [capital PureLetters]? capital: @"#";
        if ([_allkeys indexOfObject:capital] > 0 && [_allkeys indexOfObject:capital] < _allkeys.count) {
            NSInteger index = [_allkeys indexOfObject:capital];
            NSMutableArray *deleteArr = [_contactDic objectForKey:_allkeys[index]];
            if (contactInfo.indexPath != nil) {
                [deleteArr removeObjectAtIndex:contactInfo.indexPath.row - 1];
            }
            [deleteArr addObject:contactInfo.modelOfChange];
            
            [self archiverFile:_contactDic];
            [_tableView reloadData];
        } else {
            if (contactInfo.indexPath != nil) {
                [self deleteContactAtIndexPath:contactInfo.indexPath andTableView:_tableView];
            }
            NSMutableArray *addArr = [NSMutableArray array];
            [_contactDic setObject:addArr forKey:capital];
            [addArr addObject:contactInfo.modelOfChange];
            _allkeys = [[_contactDic allKeys]sortedArrayUsingSelector:@selector(compare:)];
            [self archiverFile:_contactDic];
            [_tableView reloadData];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
